<template>
    <div class="hc-container">
        <el-dialog class="choice-tab-style" v-if="popup" :close-on-click-modal="false"
                   :title="modalConfig.modalTitle || '请选择' "
                   style="text-align: left" :visible.sync="popup">
            <div class="tab-data-tree">
                <el-tabs v-model="activeName" v-show="modalConfig.tabData && modalConfig.tabData.length != 0"
                         @tab-click="handleClick">
                    <el-tab-pane :label="preTabItem.title" v-for="(preTabItem,index) in modalConfig.tabData"
                                 :name="preTabItem.name" :key="index">
                        <div class="tab-list">
                            <!-- 搜索框 -->
                            <el-input class="search-input" placeholder="搜索" size="mini" v-model="searchKeyword">
                                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            </el-input>
                            <el-scrollbar class="scroll-Y">
                                <el-tree class="filter-tree" :data="preTabItem.treeData"
                                         @check-change="handleCheckChange"
                                         :props="{ label: preTabItem.replaceFields.label }"
                                         :node-key="preTabItem.replaceFields.value"
                                         :expand-on-click-node="false"
                                         :highlight-current="true"
                                         :check-on-click-node="true"
                                         :check-strictly="true"
                                         :filter-node-method="filterNode" :ref="preTabItem.name"
                                         :show-checkbox="preTabItem.replaceFields.showCheckbox"
                                         :default-expand-all="preTabItem.replaceFields.expandAll">
                                </el-tree>
                            </el-scrollbar>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <div class="tab-data-prepare" v-if="!showPrepare">
                <div v-if="showPrepare" class="tab-data-button-group">
                    <el-button type="primary" @click="chooseData" icon="el-icon-arrow-right">选中</el-button>
                </div>
                <div v-else>
                    <div style="display: flex;align-items: center;padding: 15px 10px 0 10px;">
                        <div>
                            <el-checkbox v-model="checkAll" v-if="modalConfig.multi" :indeterminate="isIndeterminate"
                                         @change="handleCheckAllChange">全选
                            </el-checkbox>
                        </div>
                        <el-input class="search-input" placeholder="搜索" size="mini" v-model="childSearchKey">
                            <i slot="suffix" class="el-input__icon el-icon-search"
                               style="font-size:16px;cursor: pointer; margin-top: 2px;"></i>
                        </el-input>
                    </div>
                    <el-scrollbar class="scroll-Y">
                        <el-checkbox-group v-model="checkData">
                            <el-checkbox class="check-item" @change="onChangeCheckBox"
                                         v-for="(pre_item, index) in tempCheckData"
                                         :label="pre_item[childReplaces.label] + '_' + pre_item[childReplaces.value] + '_' + activeName"
                                         :key="index">{{
                                pre_item[childReplaces.label]}}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-scrollbar>
                </div>
            </div>
            <div class="tab-data-list">
                <div class="tab-title" style="line-height:32px;font-weight: 700">
                    当前所选数据({{ checkData.length }})
                    <el-button size="mini" round @click="clearChoice">清空选择</el-button>
                </div>
                <el-scrollbar class="scroll-Y-List">
                    <div class="checkList" v-for="(preTab,index) in modalConfig.tabData" :key="index"
                         v-show="preTab.choiceData && preTab.choiceData.length != 0">
                        <span class="checkTitle">{{preTab.title}}</span>
                        <div class="choice-item" v-for="(preItem,i) in preTab.choiceData"
                             :label="preItem"
                             :key="i">
                            {{preItem.split("_")[0]}}
                            <i class="el-icon-circle-close btn-check-close"
                               @click="handleDelNode(preTab.choiceData,preItem)"/>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleOk">确定</el-button>
                <el-button @click="handleCancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

    // 数据格式保持为 label_value_name
    import request from '@/utils/request'
    import PinYinMatch from "pinyin-match";

    export default {
        data()
        {
            return {
                popup: false, // 是否显示
                modalConfig: {}, // 配置
                promiseStatus: null, // 异步状态
                choiceData: {}, // 已选择数据
                activeName: '', // 当前选中的tab
                searchKeyword: '', // 关键字搜索
                showPrepare: true, // 显示备选框
                childReplaces: {}, // 备选栏的配置
                childTempData: [], // 备选栏的数据
                tempCheckData: [], // checkGroup中的数据
                checkData: [], // 备选栏选择的数据
                checkAll: false, // 是否全选备选栏
                isIndeterminate: false, // 是否不确定全选
                childSearchKey: '', // 查询值
                requestParam: {}, // 请求参数
            }
        },
        watch: {
            searchKeyword(val)
            {
                this.$refs[this.activeName][0].filter(val)
            },
            childSearchKey(val)
            {
                let _this = this;
                _this.tempCheckData = [];
                if (val)
                {
                    _this.childTempData.map(preData =>
                    {
                        if (PinYinMatch.match(preData[_this.childReplaces.label], val))
                        {
                            _this.tempCheckData.push(preData);
                        }
                    });
                }
                else
                {
                    _this.tempCheckData = _this.childTempData;
                }
            }
        },
        methods: {
            // 打开弹窗，name为弹窗名称
            openDialog(showData, config)
            {
                console.log(showData, "=========showData", config, "=========config")
                this.modalConfig = config;
                this.popup = true;
                this.activeName = this.modalConfig.tabData[0].name;
                if (showData)
                {
                    this.modalConfig.tabData.map(preItem =>
                    {
                        // 设置初始为空数组
                        this.$set(preItem, 'choiceData', []);
                        if (showData[preItem.name] && showData[preItem.name].length != 0)
                        {
                            this.$set(preItem, 'choiceData', showData[preItem.name]);
                        }
                    });
                }
                let findObj = this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == this.activeName;
                });
                if (findObj && findObj.replaceFields && findObj.replaceFields.event)
                {
                    this.showPrepare = false;
                    this.initPrepare();
                }
                // 过滤常选人员中人员名为空的数据
                this.modalConfig.tabData.map(preTab => {
                    if (preTab.name == 'oftenPerson')
                    {
                        preTab.treeData = preTab.treeData.filter(v => v[preTab.replaceFields.label] != '');
                    }
                })
                // 创建promise
                return new Promise((resolve, reject) =>
                {
                    this.promiseStatus = {
                        resolve,
                        reject,
                    };
                });
            },
            // 切换tab页触发的事件
            handleClick(tab)
            {
                console.log("--------------切换tab--------------", tab.name, this.activeName);
                let findObj = this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == tab.name;
                });
                if (findObj && findObj.replaceFields && findObj.replaceFields.event)
                {
                    this.showPrepare = false;
                    this.initPrepare();
                }
                else
                {
                    this.showPrepare = true;
                }
            },
            //点击选择
            handleCheckChange(data, checked, indeterminate)
            {
                let _this = this;
                var findTabObj = this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == _this.activeName;
                });
                if (findTabObj && findTabObj.replaceFields && findTabObj.replaceFields.event)
                {
                    _this.commonRequest(findTabObj.replaceFields.event, data, findTabObj.replaceFields, findTabObj);
                }
                else
                {
                    if (checked) // 选中
                    {
                        _this.modalConfig.tabData.map((preTab, index) =>
                        {
                            if (_this.modalConfig.multi == false) // 若为单选，则对之前所选数据进行清空
                            {
                                let checkKeys = _this.$refs[preTab.name][0].getCheckedKeys();
                                checkKeys.map(item =>
                                {
                                    console.log(item, data[preTab.replaceFields.value], preTab.name)
                                    if (item != data[preTab.replaceFields.value] || _this.activeName != preTab.name)
                                    {
                                        _this.$refs[preTab.name][0].setChecked(item, false,false)
                                    }
                                });
                            }
                        });
                        this.chooseData()
                    }
                    else
                    {
                        this.modalConfig.tabData.map(preTab =>
                        {
                            if(preTab.name == _this.activeName){
                                preTab.choiceData=preTab.choiceData.filter(item=>item.indexOf(data[findTabObj.replaceFields.value])<0)
                            }
                        });
                    }
                }
            },
            //执行删除选中节点
            handleDelNode(P_ChoiceData, P_Item)
            {
                console.log(P_ChoiceData, P_Item);
                let tempIndex = P_ChoiceData.indexOf(P_Item);
                P_ChoiceData.splice(tempIndex, 1);
                let curChooseData = this.$refs[this.activeName][0].getCheckedNodes();
                let findTabObj = this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == this.activeName;
                });
                curChooseData.map(preChoseData =>
                {
                    if(!P_ChoiceData.some(item=>item.indexOf(preChoseData[findTabObj.replaceFields.value])>-1)){
                        this.$refs[this.activeName][0].setChecked(preChoseData[findTabObj.replaceFields.value], false);
                    }

                });
            },
            //清空选择
            clearChoice()
            {
                const _this = this;
                _this.modalConfig.tabData.map(preTab =>
                {
                    // 清空树选择的数据
                    let checkKeys = _this.$refs[preTab.name][0].getCheckedKeys();
                    checkKeys.map(item =>
                    {
                        _this.$refs[preTab.name][0].setChecked(item, false)
                    });
                    _this.$set(preTab, 'choiceData', []);
                    if (_this.checkData.length != 0)
                    {
                        _this.checkData = [];
                        _this.isIndeterminate = false;
                        _this.checkAll = false;
                    }
                });
            },
            // 查询tree
            filterNode(value, data)
            {
                let findObj = this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == this.activeName;
                });
                if (!findObj) return true;
                let fieldName = findObj.replaceFields.label;
                if (!value || !fieldName) return true;
                return PinYinMatch.match(data[fieldName], value);
            },
            //确认按钮
            handleOk()
            {
                // 返回选中的数据
                this.modalConfig.tabData.map(preTab =>
                {
                    this.choiceData[preTab.name] = preTab.choiceData;
                });
                console.log(this.modalConfig, this.choiceData)
                this.promiseStatus.resolve(this.choiceData);
                this.destroyElement();
            },
            //取消按钮
            handleCancel()
            {
                //清空勾选项
                this.promiseStatus.reject({
                    msg: "取消",
                });
                this.destroyElement();
            },
            //销毁组件
            destroyElement()
            {
                this.popup = false;
            },
            //点击树的公用请求
            commonRequest(event, data, replaceFields, tabObj)
            {
                console.log(event, "event", data, "data", replaceFields, "replaceFields");
                // 对参数进行解析
                let params = this.getParamsObjByEventParams(event.params, data);
                this.requestParam = {
                    url: event.path,
                    method: event.methodName,
                    params: params
                };
                console.log(this.requestParam);
                request(this.requestParam).then(res =>
                {
                    console.log(res, "点击事件树，返回的数据");
                    let resConfig = JSON.parse(replaceFields.replaceFields);
                    let data = res;
                    let expand = resConfig.result.split(".");
                    if (expand.length != 0)
                    {
                        for (let str of expand)
                        {
                            data = data[str];
                        }
                    }
                    this.childTempData = data;
                    this.tempCheckData = data;
                    this.childReplaces = {
                        label: resConfig.label,
                        value: resConfig.value
                    };
                    console.log(this.childTempData, this.childReplaces, tabObj);
                    this.checkData = tabObj.choiceData;
                }).catch(err =>
                {

                });
            },
            //解析字段
            getParamsObjByEventParams(params, record)
            {
                if (!params)
                {
                    return {};
                }
                let tempObj = {};
                // console.log(params, record);
                if (record && record.constructor === Object)
                {
                    Object.keys(params).forEach((key) =>
                    {
                        if (
                            params[key] &&
                            params[key].constructor === String &&
                            params[key].indexOf("@") != -1
                        )
                        {
                            // console.log(params[key])
                            tempObj[key] = record[params[key].replace("@", "")];
                        }
                        else
                        {
                            tempObj[key] = params[key];
                        }
                    });
                }
                return tempObj;
            },
            //checkBox选择后数据改变的回调
            onChangeCheckBox(val)
            {
                let _this = this;
                console.log(_this.checkData, val, "=========");
                if (_this.modalConfig.multi == false) // 单选
                {
                    this.checkData = [this.checkData[this.checkData.length - 1]];
                    _this.modalConfig.tabData.map(preTab =>
                    {
                        _this.$set(preTab, 'choiceData', []);
                    });
                }
                if (_this.checkData.length != 0)
                {
                    _this.isIndeterminate = true;
                    if (_this.checkData.length == _this.childTempData.length)
                    {
                        _this.isIndeterminate = false;
                        _this.checkAll = true;
                    }
                }
                else
                {
                    _this.isIndeterminate = false;
                    _this.checkAll = false;
                }
                let findTabObj = _this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == _this.activeName;
                });
                if (!findTabObj.choiceData)
                {
                    _this.$set(findTabObj, 'choiceData', []);
                }
                findTabObj.choiceData = _this.checkData;
            },
            //全选
            handleCheckAllChange(val)
            {
                let _this = this;
                if (JSON.parse(val)) // 多选
                {
                    _this.childTempData.map(preData =>
                    {
                        _this.checkData.push(preData[_this.childReplaces.label] + "_" + preData[_this.childReplaces.value] + "_" + _this.activeName);
                    })
                }
                else // 取消多选
                {
                    _this.checkData = [];
                }
                _this.isIndeterminate = false;
                let findTabObj = _this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == _this.activeName;
                });
                if (!findTabObj.choiceData)
                {
                    _this.$set(findTabObj, 'choiceData', []);
                }
                findTabObj.choiceData = _this.checkData;
            },
            //选择数据
            chooseData()
            {
                let _this = this;
                if (_this.modalConfig.multi == false) // 单选
                {
                    _this.modalConfig.tabData.map(preTab =>
                    {
                        _this.$set(preTab, 'choiceData', []);
                    });
                }
                let findTabObj = _this.modalConfig.tabData.find(preTab =>
                {
                    return preTab.name == _this.activeName;
                });
                let curChooseData = _this.$refs[_this.activeName][0].getCheckedNodes();
                console.log(findTabObj, curChooseData)
                if (!findTabObj.choiceData)
                {
                    _this.$set(findTabObj, 'choiceData', []);
                }
                // 将树中选择的数据转移至右侧备选区，并清空树选择
                curChooseData.map(preChoseData =>
                {
                    let preTemp = preChoseData[findTabObj.replaceFields.label] + "_" + preChoseData[findTabObj.replaceFields.value] + "_" + findTabObj.name
                    let findObj = findTabObj.choiceData.find(preData =>
                    {
                        return preData == preTemp
                    });
                    if (!findObj)
                    {
                        findTabObj.choiceData.push(preTemp);
                    }
                    // _this.$refs[_this.activeName][0].setChecked(preChoseData[findTabObj.replaceFields.value], false);
                });
            },
            //初始化备选区数据
            initPrepare()
            {
                this.childReplaces = {};
                this.childTempData = [];
                this.tempCheckData = [];
                this.checkData = [];
                this.checkAll = false;
                this.isIndeterminate = false;
                this.childSearchKey = '';
                this.requestParam = {};
            }
        }
    }
</script>

<style lang="scss" scoped>
    .choice-tab-style {

        .tab-data-tree {
            width: 40%;

            ::v-deep .el-tabs {
                width: 100%;
                padding: 0px 15px 0px 15px;
                border-right: 1px solid #e6ebf5;
                height: 100%;
            }
        }

        .tab-data-prepare {
            width: 30%;
            border-right: 1px solid #e6ebf5;

            .scroll-Y {
                height: 335px;
                margin-top: 10px;

                ::v-deep .el-scrollbar__wrap {
                    overflow-x: hidden;
                }
            }

            .check-item {
                display: block;
                height: 26px;
                line-height: 26px;
                padding-left: 25px;
            }
        }

        .tab-data-list {
            flex:1;

            .tab-title {
                width: 96%;
                margin: 20px 2% 0px 2%;
                height: 32px;
                display: flex;
                justify-content: space-between;
            }

            .choice-item {
                display: block;
                height: 26px;
                line-height: 26px;
                padding-left: 25px;
            }

            .checkTitle {
                padding-left: 10px;
                color: darkgray;
                height: 28px;
                line-height: 28px;
            }

            .btn-check-close {
                cursor: pointer;
                color: red;
                font-size: 14px;
            }

            .scroll-Y-List {
                height: 330px;
                margin-top: 10px;

                ::v-deep .el-scrollbar__wrap {
                    overflow-x: hidden;
                }
            }
        }

        ::v-deep .el-dialog__body {
            border-radius: 3px;
            display: flex;
            border: 1px solid #e6ebf5;
            margin: 10px;
            padding: 0px 0px 0px;
            height: 400px;
        }

        .search-input {
            display: flex;
            align-items: center;
            width: 70%;
            margin: 0 0 0 20px;
            height: 32px;

            ::v-deep .el-input__inner {
                border-radius: 100px;
            }
        }
    }

    .tab-list .scroll-Y {
        height: 300px;
        margin-top: 10px;

        ::v-deep .el-scrollbar__wrap {
            overflow-x: hidden;
        }
    }


    .hc-container {
        ::v-deep .el-dialog {
            margin-top: 12vh !important;
            width: 60% !important;
        }

        .tab-data-button-group {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }

</style>